<?php

namespace Modules\System\Http\Controllers;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Validator;
use Modules\System\Models\ConfigModel;
use Modules\System\Models\UploadFileModel;
use Modules\System\Services\Mds\MDSCurl;
use Modules\System\Services\Mds\MDSZip;

/**
 * 文件相关类
 */
class Upload extends Controller
{
    /**
     * 上传列表页
     * @return Renderable
     * http://l.com/system/upload/index
     */
    public function index(){

        if(empty($_GET['field'])){
            $_GET['field'] = "field";
        }

        $data['field'] = $_GET['field'];                                        //用来确定返回的字段定位值用。
        $data['fieldVal'] = isset($_GET['fieldVal']) ? $_GET['fieldVal'] : "";  //已经选中的那些图片，直接在选择中显示

        $data['singleDouble'] = isset($_GET['singleDouble']) ? $_GET['singleDouble'] : "double";  //是单选还是多选
        $data['showOld'] = isset($_GET['showOld']) ? $_GET['showOld'] : "0";  //是否显示老数据

        //d($data);

        return view('system::Upload/index',$data);

    }

    /**
     * 上传接口
     * @return Renderable
     * http://cheyoukong.1zhetejia.com/system/upload/image
     */
    public function image(){

        ini_set('display_errors',E_ALL);
        //print_r($_FILES);exit;
        //$uniqidstr = uniqid(); //13位的字符串

        $strdir = date('Y');
        if(!file_exists('./upload/' . $strdir)){
            mkdir('./upload/' . $strdir,0777,true);
        }

        $extension = strrchr($_FILES['file']['name'],'.');
        //$name = time().'mds'.$uniqidstr;

        $name = md5_file($_FILES['file']['tmp_name']);

        //查询本图片是否已经被上传过
        $file = UploadFileModel::where("md5",$name)->first();

        if(!isset($file->file_id)){

            $config = ConfigModel::getKV('application');
            if(isset($config['cos_open']) && $config['cos_open'] == 1){
                //上传到对象云存储::oos######################
                $fileCos = MDSCurl::post("http://" . $_SERVER['HTTP_HOST'] . '/support/cos.php',['srcPath' => $_FILES['file']['tmp_name'],"secretKey" => "leapmary"]);
                $fileCos = json_decode($fileCos,true);
                if($fileCos['code'] == 400){
                    mdsResponse(400,"对象存储错误");
                }
                $fileCos['Location'] = "https://" . $fileCos['Location'];
                //上传到对象云存储::oos######################
            }

            //缓存图片文件移动到网站下面。
            move_uploaded_file($_FILES['file']['tmp_name'],'./upload/' . $strdir . '/' . $name . $extension);

            if(isset($fileCos)){
                $img['picture_address'] = $fileCos['Location'];
            }else{
                $img['picture_address'] = '/upload/' . $strdir . '/' . $name . $extension;
            }

            $i_data = [
                'storage' => "local",
                'group_id' => 1,
                'file_url' => $img['picture_address'],
                'file_name' => $name,
                'file_size' => $_FILES['file']['size'],
                'file_type' => $_FILES['file']['type'],
                'extension' => $extension,
                'is_user' => 1,
                'is_recycle' => 0,
                'is_delete' => 0,
                'modules' => 'system',
                'md5' => $name,
                'create_time' => time(),
            ];

            //print_r($i_data);exit;

            $img['file_id'] = UploadFileModel::insertGetId($i_data);

        }else{

            //如果已经上传过更新本图片sort值最大。
            $file_max = UploadFileModel::orderBy('sort','desc')->first();
            $num = $file_max['sort'] + 1;

            $re = UploadFileModel::where("file_id",$file->file_id)->update(['sort' => $num]);

            $img['picture_address'] = $file->file_url;
            $img['file_id'] = $file->file_id;

        }

        mdsResponse(200,"上传成功",$img);

    }

    /**
     * 请求图片数据ajax
     * @return Renderable
     * http://l.com/system/upload/index_ajax
     */
    public function index_ajax(Request $request){

        $i = $request->input();

        //$fieldValArr = explode(",",$i['fieldVal']);
        //d($i['fieldVal']);

        //如果是单的就不筛选图片，显示全部。
//        if($i['type'] == 'single'){
//            unset($i['fieldVal']);
//        }

        $file = UploadFileModel::orderBy('sort','desc')
            ->where(function($query) use ($i){
                if(isset($i['showOld']) && $i['showOld'] != 1){
                    //$fieldValArr = explode(",",$i['fieldVal']);
                    $query->whereIn("file_url",$i['fieldVal']);
                }
            })->orderBy('file_id','desc')
            ->limit(20)
            ->get()
            ->toJson();

        echo '{
            "code": 1,
            "msg": "success",
            "url": "",
            "data": {
                "group_list": [{
                    "group_id": 10066,
                    "group_type": "image",
                    "group_name": "云存储",
                    "sort": 100,
                    "is_delete": 0,
                    "wxapp_id": 10001,
                    "create_time": "2020-03-25 14:11:52",
                    "update_time": "2020-03-25 14:11:52"
                }],
                    "file_list": {
                        "total": 2132,
                        "per_page": 32,
                        "current_page": 1,
                        "last_page": 67,
                        "data": ' . $file . '
                    }
                }
            }';

    }

    /**
     * 删除接口
     * @return Renderable
     */
    public function del(Request $request){

        $i = $request->input();
        $choice_img = explode(",",$i['choice_img']);

        $re = UploadFileModel::whereIn("file_url",$choice_img)->delete();

        mds_if_response($re);

    }


    /**
     * 下载压缩文件接口
     * http://cheyoukong.1zhetejia.com/system/upload/downloadZip?file=/upload/2021/016cbf31f5a34e98b5b7ba25dd73a4cd.jpg,,,,/upload/2021/2bcca3d90a438a5d4ef5e2051439256b.jpg
     */
    public function downloadZip(Request $request){

        $i = $request->input();

        $validator = Validator::make(
            $i,
            [
                'file' => "required",
                'id' => "required",
            ],
            [
                'file.required' => '区别id不能为空',
            ]
        );

        if(!empty($validator->errors()->first())){
            mdsResponse(400,$validator->errors()->first());
        }

        $file = array_filter(explode(",",$i['file']));

        //跳去打包下载
        MDSZip::zip("photograph" . $i['id'],$file);

    }


}
